﻿using JewererBasic.Classes;
using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace JewererBasic.Controllers
{
    public class WasteReportController : Controller
    {      
        public ActionResult Index()
        {
            return View(Waste_Report_BO.GetAllReport());
        }

        public ActionResult CreateReport()
        {
            WASTE_REPORT wr=Waste_Report_BO.CreateReport();
            return RedirectToAction("ExportReportWasteById", new { id = wr.Id });
        }

        public ActionResult Detail(int waste_report_id)
        {
            return View(Waste_Report_BO.GetReport(waste_report_id));
        }

        public PartialViewResult GetCurrentWaste()
        {
            return PartialView("_Current_Waste");
        }

        public ActionResult ExportReportWasteById(int id = -1)
        {
            if (id != -1)
            {
                //id = 1;
                MSQDBEntities db = new MSQDBEntities();
                ReportDataSource rds = new ReportDataSource("DSWasteReportById", db.GetWasteReportById(id));

                // Set up viewer
                ReportViewer viewer = new ReportViewer();
                viewer.ProcessingMode = ProcessingMode.Local;
                viewer.LocalReport.ReportPath = Server.MapPath("~/Reports" + "//RPWasteReportById.rdlc");
                viewer.LocalReport.DataSources.Add(rds);

                // Variables
                Warning[] warnings;
                string[] streamIds;
                string mimeType = string.Empty;
                string encoding = string.Empty;
                string extension = string.Empty;
                byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
                Response.Buffer = true;
                Response.Clear();
                Response.ContentType = mimeType;
                Response.AddHeader("content-disposition", "attachment; filename=" + "Waste_Report" + "." + extension);
                Response.BinaryWrite(bytes); // create the file
                Response.Flush(); // send it to the client to download
                return File(bytes, "application/pdf");
            }
            else
            {
                // Infor no waste in this month
            }
            //ErrorLog.Instance.InternalErrors.Clear();
            ErrorLog.Instance.InternalErrors.Add("There is no Waste.");
            return RedirectToAction("Index", "Error");
        }
    }
}
